package com.gobo.msmservice.controller;

import com.gobo.commonutils.R;
import com.gobo.commonutils.RandomUtil;
import com.gobo.msmservice.service.MsmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/msmservice")
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {
        phone = "register"+phone;
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) {
            return R.ok();
        }
        code = RandomUtil.getSixBitRandom();
        //加入Redis缓存中  设置5分钟过期时间
        Boolean isSend = msmService.sendMsmCode(phone,code);
        if(isSend){
            redisTemplate.opsForValue().set(phone,code,5L, TimeUnit.MINUTES);


            //TODO  这里验证码直接返回在接口中
            return R.ok().message("短信验证码发送成功").data("code",code);
        }else {
            return R.error().message("短信验证码发送失败");
        }
    }
}